package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.BackTimeDAO;
import mwa.cs.dao.ReceivePositionDAO;
import mwa.cs.dao.RequestTypeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.SMPackageDAO;
import mwa.cs.dao.SitesDAO;
import mwa.cs.dao.UserLoginDAO;
import mwa.cs.database.Database;
import mwa.cs.model.BackTime;
import mwa.cs.model.MailProperties;
import mwa.cs.model.ReceivePosition;
import mwa.cs.model.Sites;
import mwa.cs.util.JDate;
import mwa.cs.util.Mail;

public class CS85000Srvl extends HttpServlet implements Servlet {
	
	private Database db;
	private String vaAgentBrowser;
	private String vaUrlAddress;
	private int vnSiteId;
	private int vnUserId;


    public CS85000Srvl() {
        super();
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	// get site_id
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
    	vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    	String vaProcessType = request.getParameter("process_type");
		if(vaProcessType.equals("getDataTable")){
			getDataTable(request,response);
		}
		else if(vaProcessType.equals("addSite"))
		{
			addSite(request,response);
		}
		else if(vaProcessType.equals("editSite"))
		{
			editSite(request,response);
		}
		else if(vaProcessType.equals("deleteSite"))
		{
			deleteSite(request,response);
		}
		else if(vaProcessType.equals("getPackage")){
			getPackageName(request,response);
		}
    }

    private void getPackageName(HttpServletRequest request,HttpServletResponse response)  throws ServletException, IOException  {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
    	String[] vaMessage = null, vaValue = null;
    	this.db = new Database();
    	
    	SMPackageDAO voPackageDAO = new SMPackageDAO(db);
		List<Map<String, Object>> voResult = (List<Map<String, Object>>) voPackageDAO.findAll(1, -1);
		
		
		
		vaValue = new String[voResult.size()];
		vaMessage = new String[voResult.size()];
			for (int i = 0; i < voResult.size(); i++) {
				Map<String, Object> voObject = voResult.get(i);	
				vaValue[i] =    String.valueOf(voObject.get("PACKAGE_ID"));
				vaMessage[i] = (String) voObject.get("PACKAGE_NAME");	
			}
    	
    	JSONObject voObject = new JSONObject();
		JSONArray voList = new JSONArray();
		PrintWriter voOut = response.getWriter();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i ++) {
				voList.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voList);
		JSONArray voList2 = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i ++) {
				voList2.add(vaValue[i]);
			}
		}
		voObject.put("values", voList2);
		
		db.close();
		voOut.print(voObject.toJSONString());
		
	}

	public void getDataTable(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());

		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			// return empty
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
			return;
		}
		
		SitesDAO voDao = new SitesDAO(db);
		List<Map<String, Object>> voListFindAll = voDao.findAllJoinPackage();
		
		if(voListFindAll == null || voListFindAll.size() == 0)
		{
			// return empty
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
			return;
		}

		for (int i = 0; i < voListFindAll.size(); i++) 
		{
			Map<String, Object> mapItem = (Map<String, Object>) voListFindAll.get(i);
			
			voColumn = new JSONArray();
			voColumn.add(i + 1);
			voColumn.add(mapItem.get("SITE_ID").toString());
			voColumn.add(mapItem.get("SITE_NAME").toString());
			String packageName = "";
			if(mapItem.get("PACKAGE_NAME")!=null){
				packageName = mapItem.get("PACKAGE_NAME").toString();
			}
			voColumn.add(packageName);
			voRow.add(voColumn);
		}

		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
		
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
    
    public void addSite(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		PrintWriter voOut = response.getWriter();
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voOut.print("connect_db_fail");
			return;
		}
		
		int vnSiteId2 = Integer.parseInt(request.getParameter("siteId").toString());
		String vaSiteName = request.getParameter("siteName").toString();
		int vnPackageId =0;
		if(request.getParameter("packageId".toString())!=""||!request.getParameter("packageId".toString()).equals("")){
			vnPackageId = Integer.parseInt(request.getParameter("packageId".toString()));
		}
		
		
		JDate voJDate = new JDate();
		String vaDate = voJDate.getDate();
		String vaTime = voJDate.getTime();
		
		Sites voSites = new Sites();
		voSites.setVnSiteId(vnSiteId2);
		voSites.setVaSiteName(vaSiteName);
		voSites.setVnInsertUserId(vnUserId);
		voSites.setVaInsertDate(vaDate);
		voSites.setVaInsertTime(vaTime);
		voSites.setVnUpdateUserId(vnUserId);
		voSites.setVaUpdateDate(vaDate);
		voSites.setVaUpdateTime(vaTime);
		voSites.setPackageId(vnPackageId);
		
		SitesDAO voDao = new SitesDAO(db);
		boolean vbIsDuplicate = voDao.isDuplicate(vnSiteId2, vaSiteName);
		
		if(vbIsDuplicate)
		{
			db.close();
			// Return duplicate
			voOut.print("duplicate");
		}
		else
		{
			try
			{
				db.beginTransaction();
				voDao.addSites(voSites);
				db.commit();
				voOut.print("success");
			}
			catch(Exception ex)
			{
				SMErrorLogDAO.getInstance().addLog(0, "CS85000", JDate.getDate(), JDate.getTime(),vnUserId, "CS85000Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				voOut.print("fail");
			} finally{
				db.close();
			}
		}
    }
    
    public void editSite(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		PrintWriter voOut = response.getWriter();
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voOut.print("connect_db_fail");
			return;
		}
		
		int vnSiteId2 = Integer.parseInt(request.getParameter("siteId").toString());
		String vaSiteName = request.getParameter("siteName").toString();
		int vnOldSiteId = Integer.parseInt(request.getParameter("oldSiteId").toString());
		int vnPackageId =0;
		if(request.getParameter("packageId".toString())!=""||!request.getParameter("packageId".toString()).equals("")){
			vnPackageId = Integer.parseInt(request.getParameter("packageId".toString()));
		}

		
		SitesDAO voDao = new SitesDAO(db);
		
		// เช็ค site_id ที่จะอัพเดทว่ามีอยู่ในระบบหรือไม่
		Map<String, Object> voOldSiteObj = (Map<String, Object>)voDao.findSitesBySiteId(vnOldSiteId);
		if(voOldSiteObj == null)
		{
			// ไม่มี site_id อยู่ในระบบแล้ว
			db.close();
			voOut.print("no_site");
		}
		else
		{
			JDate voJDate = new JDate();
			String vaDate = voJDate.getDate();
			String vaTime = voJDate.getTime();
			
			Sites voSites = new Sites();
			
			voSites.setVnSiteId(vnSiteId2);
			voSites.setVaSiteName(vaSiteName);
			voSites.setVaTaxId(voOldSiteObj.get("TAX_ID") == null? null : voOldSiteObj.get("TAX_ID").toString());
			voSites.setVaTaxBranch(voOldSiteObj.get("TAX_BRANCH") == null ? null : voOldSiteObj.get("TAX_BRANCH").toString());
			voSites.setVaAddress(voOldSiteObj.get("ADDRESS") == null ? null : voOldSiteObj.get("ADDRESS").toString());
			voSites.setVaCityCode(voOldSiteObj.get("CITY_CODE") == null ? null : voOldSiteObj.get("CITY_CODE").toString());
			voSites.setVaDistrictCode(voOldSiteObj.get("DISTRICT_CODE") == null ? null : voOldSiteObj.get("DISTRICT_CODE").toString());
			voSites.setVaProvinceCode(voOldSiteObj.get("PROVINCE_CODE") == null ? null : voOldSiteObj.get("PROVINCE_CODE").toString());
			voSites.setVaPostCode(voOldSiteObj.get("POST_CODE") == null ? null : voOldSiteObj.get("POST_CODE").toString());
			voSites.setVaTelephone(voOldSiteObj.get("TELEPHONE") == null ? null : voOldSiteObj.get("TELEPHONE").toString());
			voSites.setVaFax(voOldSiteObj.get("FAX") == null ? null : voOldSiteObj.get("FAX").toString());
			voSites.setVaHeadName(voOldSiteObj.get("HEAD_NAME") == null ? null : voOldSiteObj.get("HEAD_NAME").toString());
			voSites.setVaHeadPosition(voOldSiteObj.get("HEAD_POSITION") == null ? null : voOldSiteObj.get("HEAD_POSITION").toString());
			voSites.setVaHomeNumber(voOldSiteObj.get("INSERT_USER_ID") == null ? null : voOldSiteObj.get("INSERT_USER_ID").toString());
			voSites.setVnUpdateUserId(vnUserId);
			voSites.setVaUpdateDate(vaDate);
			voSites.setVaUpdateTime(vaDate);
			voSites.setPackageId(vnPackageId);
			
			// ถ้า site_id อันใหม่ กับ อันเก่า ไม่เหมือนกัน  เช็คว่าอันใหม่ซ้ำในระบบหรือไม่
			if(vnSiteId2 != vnOldSiteId)
			{
				boolean isDuplicate = voDao.isDuplicate(vnSiteId2, vaSiteName);
				if(isDuplicate)
				{
					db.close();
					voOut.print("duplicate");
				}

			}
			else
			{
				try
				{
					db.beginTransaction();
					voDao.updateSitesAllAtributes(vnOldSiteId, voSites);
					db.commit();
					voOut.print("success");
				}
				catch(Exception ex)
				{
					SMErrorLogDAO.getInstance().addLog(0, "CS85000", JDate.getDate(), JDate.getTime(),vnUserId, "CS85000Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);
					voOut.print("fail");
				} finally{
					db.close();
				}
			}
		}
    }
    
    public void deleteSite(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		PrintWriter voOut = response.getWriter();
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voOut.print("connect_db_fail");
			return;
		}
		
		int vnSiteId2 = Integer.parseInt(request.getParameter("siteId").toString());
		
		SitesDAO voDao = new SitesDAO(db);
		
		// เช็ค site_id ที่จะอัพเดทว่ามีอยู่ในระบบหรือไม่
		Map<String, Object> voSiteObj = (Map<String, Object>)voDao.findSitesBySiteId(vnSiteId2);
		if(voSiteObj == null)
		{
			// ไม่มี site_id อยู่ในระบบแล้ว
			db.close();
			voOut.print("no_site");
		}
		else
		{
			try
			{
				db.beginTransaction();
				voDao.deleteSite(vnSiteId2);
				db.commit();
				voOut.print("success");
			}
			catch(Exception ex)
			{
				SMErrorLogDAO.getInstance().addLog(0, "CS85000", JDate.getDate(), JDate.getTime(),vnUserId, "CS85000Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				voOut.print("fail");
			} finally{
				db.close();
			}
		}
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
}
